package com.cqjtu.education.utils;


import cn.dev33.satoken.stp.StpUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Author: 冉鹏
 * @Date: 2022/4/21 22:20
 */
@Component
public class SaTokenInterceptor implements HandlerInterceptor {

    @Resource
    Response res;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //日常测试，先取消拦截器
//        System.out.println("取消拦截器");
//        System.out.println(request.getRequestURI());
//        return true;
        //开启拦截器
        System.out.println("进入拦截器");
        //请求url
        System.out.println(request.getRequestURI());
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response.setStatus(HttpStatus.OK.value());
            System.out.println("预检请求");
            return false;
        }
        if (StpUtil.isLogin()) {
            try {
                StpUtil.checkActivityTimeout();
                StpUtil.updateLastActivityToNow();
            } catch (Exception e) {
                System.out.println("token已过期");
                res.setResponse(response, 401, "token已过期");
                return false;
            }
            String token = request.getHeader("Authorization");
            if (token == null) {
                System.out.println("请求头无token");
                res.setResponse(response, 401, "请求头无token");
                return false;
            } else {
                if (token.equals(StpUtil.getTokenValue())) {
                    System.out.println("验证token成功");
                    return true;
                } else {
                    System.out.println("验证token失败");
                    res.setResponse(response, 401, "验证token失败");
                    return false;
                }
            }
        } else {
            System.out.println("未登录");
            res.setResponse(response, 401, "未登录");
            return false;
        }
        }

}
